//
//  FTAlbumPhotosController.m
//  Decathlon
//
//  Created on 14-2-11.(相册中照片展示)
//  Copyright (c) 2014年. All rights reserved.
//

#import "FTAlbumPhotosController.h"
#import "FTAlbumPhotosCell.h"
#import "FTAlbumPhotoControllerDelegate.h"
//#import "UIView+RCSToast.h"
#import "FTPhotoCropViewController.h"
#import "UIColor+Additions.h"
#import "RCSAlubmButton.h"
//#import "RCSFinishedSelectFileDelegate.h"
//#import "RCSBaseAlertView.h"
#import <AVFoundation/AVFoundation.h>
#import "RCSBrowserVideoViewController.h"
//#import "RCSChatViewAuxiliary.h"


static const CGFloat kFooterViewHeight = 44.0f;
static const CGFloat kPhotoViewHeight  = 78.f;
static const CGFloat kBtnPaddingLeft   = 15.0f;
static const CGFloat kBtnPaddingTop    = 10.0f;
static const CGFloat KBtnSelWidth      = 75.0f;
static const CGFloat kBtnWidth         = 60.0f;
static const CGFloat kBtnHeight        = 32.0f;
static const CGFloat kFootBarViewHeight = 50.5f;
static ALAssetsLibrary     *_assetsLibrary = NULL;

#define kMaxAllowSelectedPhotoCount 9
#define OriginalImageTag 100000
#define OriginBtnTag    200000

@interface FTAlbumPhotosController ()<FTAlbumPhotosCellDelegate>

@property(nonatomic,strong)     __block NSMutableArray  *groupArray;
@property(nonatomic,strong)     UIButton *browerBtn;
@property(nonatomic,strong)     UIButton *originBtn;
@property(nonatomic,strong)     UIButton *sendBtn;
@property(nonatomic,assign)     BOOL isComeFromDefault;

@end

@implementation FTAlbumPhotosController
@synthesize assetsGroup = _assetsGroup;
@synthesize photosTableView = _photosTableView;
@synthesize photosArray = _photosArray;
@synthesize selectPhotosDict = _selectPhotosDict;
@synthesize selectPhotoKeys = _selectPhotoKeys;
@synthesize intMaxAllowedPhotoCount = _intMaxAllowedPhotoCount;
@synthesize browerBtn = _browerBtn;
@synthesize originBtn = _originBtn;
@synthesize sendBtn = _sendBtn;
@synthesize albumType = _albumType;
@synthesize photoCanEdit = _photoCanEdit;


- (void)dealloc
{
    self.selectPhotoKeys = nil;
    self.selectPhotosDict = nil;
    self.photosArray = nil;
    self.groupArray = nil;
    self.albumDelegate = nil;
    self.videoDelegate = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
}

/**
 *	@brief
 *
 *  初始化默认相册
 *
 *	@return	N/A
 */
-(id)initDefaultALAssetsGroup
{
    if (self = [super init])
    {
        self.groupArray = [[NSMutableArray alloc] init];
        
        self.isComeFromDefault = YES;
    }
    return self;
}

/**
 *  初始化
 *
 *  @param group 选择的相册
 *
 *  @return 对象本身
 */
- (id)initWithALAssetsGroup:(ALAssetsGroup *)group
{
    if (self = [super init])
    {
        //self.strNavTitle = @"选择图片";
        self.assetsGroup = group;
        self.isComeFromDefault = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setLeftButtonWithImageName:@"icon-3" bgImageName:nil];
    [self setRightText:@"取消"];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    if (SYSTEM_VERSION >= 7.0)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    _bPreview = NO;
    [self initPhotosTableViewUI];
    
    if (self.isComeFromDefault)
    {
        [self populatePhotoAssets];
    }
    else
    {
        [self reloadPhontos];
    }
}

/**
 *	@brief	获取系统相册
 *
 *	@return	N/A
 */ 
- (void)populatePhotoAssets
{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _assetsLibrary = [[ALAssetsLibrary alloc] init];
    });

    @autoreleasepool
    {
        __weak typeof(self) weakSelf = self;

        [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos  usingBlock:^(ALAssetsGroup *group, BOOL *stop)
         {
             //PP_LOG(@"获取相册Block回调%@",_assetsLibrary);
             if (group == nil)
             {
                 if (weakSelf.photosTableView)
                 {
                     dispatch_async(dispatch_get_main_queue(), ^{
                         
                         if (weakSelf.groupArray.count <= 0)
                         {
                             [weakSelf showTipView];
                         }
                         else
                         {
                             weakSelf.assetsGroup = [weakSelf.groupArray objectAtIndex:0];
                             [weakSelf reloadPhontos];
                         }
                     });
                 }
             }
             else
             {
                 [group setAssetsFilter:[ALAssetsFilter allAssets]];
                 
                 NSInteger count = [group numberOfAssets];//调用这个方法崩溃
                 if (count == 0)
                 {
                     return;
                 }
                 [weakSelf.groupArray addObject:group];
             }
         }
         failureBlock:^(NSError *error)
         {
             [weakSelf showNoAuthorizationView];
             
         }];
    }
}

/**
 *	@brief	刷新界面
 *
 *	@return	N/A
 */
-(void)reloadPhontos
{
    @autoreleasepool
    {
        __weak typeof(self) weakSelf = self;
        
        [_assetsGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
         {
             if (result == nil)
             {
                 return;
             }
             
             //过滤图片格式外的文件
             if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]
                 || [[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo])
             {
                 [weakSelf.photosArray addObject:result];
             }
         }];
        
        //[self setStrNavTitle:(NSString *)[self.assetsGroup valueForProperty:ALAssetsGroupPropertyName]];
        
        [self performSelectorOnMainThread:@selector(reloadTableView) withObject:nil waitUntilDone:YES];
        [self scrollToBottom:NO];
    }
}

/**
 *无本地图片时提示界面
 */
-(void)showTipView
{
    [self.photosTableView removeFromSuperview];
    
    UIView *bgView = [[UIView alloc] initWithFrame:self.view.bounds];
    bgView.backgroundColor = [UIColor clearColor];
    bgView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:bgView];
    
    UIImageView *tipViewImage = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.bounds.size.width-50)/2, (self.view.bounds.size.height-40-20)/2-50, 50, 40)];
    tipViewImage.image = [UIImage imageNamed:@"icon_picture_normal"];
    [bgView addSubview:tipViewImage];
    
    UILabel *tiplab = [[UILabel alloc] initWithFrame:CGRectMake((self.view.bounds.size.width-200)/2,tipViewImage.frame.origin.y+tipViewImage.frame.size.height + 10, 200, 20)];
    tiplab.textAlignment = NSTextAlignmentCenter;
    tiplab.backgroundColor= [UIColor clearColor];
    tiplab.font = [UIFont systemFontOfSize:15];
    tiplab.textColor = RGB(134, 139, 142);
    tiplab.text = @"还没有本地图片哦";
    [bgView addSubview:tiplab];
}


/**
 *	@brief	 没有权限，要提示给用户。
 *
 *	@return	N/A
 */
- (void)showNoAuthorizationView
{
    // 没有权限，要提示给用户。
    UILabel *lblPrompt = [[UILabel alloc] init];
    if (SYSTEM_VERSION < 6.0)
    {
        [lblPrompt setText:@"Album_NoAccessRight5"];
    }
    else
    {
        [lblPrompt setText:@"Album_NoAccessRight"];
    }
    lblPrompt.frame = CGRectMake(20, 100, [[UIScreen mainScreen] bounds].size.width - 40, 30);
    lblPrompt.numberOfLines = 0;
    lblPrompt.lineBreakMode = NSLineBreakByWordWrapping;
    [lblPrompt setFont:[UIFont systemFontOfSize:12.0f]];
    [lblPrompt setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:lblPrompt];
}

-(void)rightButtonPressed:(id)action
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(void)leftButtonPressed:(id)action
{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  初始化PhotosTableView
 */
-(void)initPhotosTableViewUI
{
    _photosArray  = [[NSMutableArray alloc] init];
    _selectPhotosDict = [[NSMutableDictionary alloc] init];
    _selectPhotoKeys = [[NSMutableArray alloc] init];
    _selAlbumPhotoKeyDict = [[NSMutableDictionary alloc] init];
    _selBrowserAlbumPhotoKeyDict = [[NSMutableDictionary alloc] init];
    
    CGRect kFrame = [UIScreen mainScreen].applicationFrame;
    
    if (self.albumType == AlbumType_MutiForSending)
    {
        _photosTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,
                                                                         0,
                                                                         kFrame.size.width,
                                                                         kFrame.size.height - kFootBarViewHeight + (SYSTEM_VERSION >= 7.0 ? 20 : 0))];
        //多选最多发送9张
        _intMaxAllowedPhotoCount = kMaxAllowSelectedPhotoCount;
        [self initFootView];
    }
    else
    {
        _photosTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,
                                                                         0,
                                                                         kFrame.size.width,
                                                                         kFrame.size.height + (SYSTEM_VERSION >= 7.0 ? 20 : 0))];
    }
    
    _photosTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _photosTableView.dataSource = self;
    _photosTableView.delegate = self;
    _photosTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _photosTableView.backgroundColor = [UIColor clearColor];
    
    UIEdgeInsets insets = UIEdgeInsetsMake(0.0f, 0.0f, 20.0f, 0.0f);
    _photosTableView.contentInset = insets;
    [_photosTableView setNeedsDisplay];
    
    [self.view addSubview:_photosTableView];
}

/**
 *  绘制底部工具栏预览、原图、发送
 */
-(void)initFootView
{
    UIColor *textcolor = [UIColor rcsColorWithHexString:@"#ffffff"];
    
    CGRect rect = [UIScreen mainScreen].applicationFrame;

	UIImageView *footerView = [[UIImageView alloc] initWithFrame:CGRectMake(0,
																			rect.size.height - kFooterViewHeight - kFootBarViewHeight,
																			rect.size.width,
																			kFootBarViewHeight)];
    footerView.userInteractionEnabled = YES;
	footerView.image = [[UIImage imageNamed:@"message_bottom_bg"] stretchableImageWithLeftCapWidth:0 topCapHeight:1];
    [self.view addSubview:footerView];
    
    _browerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _browerBtn.frame = CGRectMake(kBtnPaddingLeft, kBtnPaddingTop, kBtnWidth, kBtnHeight);
    _browerBtn.showsTouchWhenHighlighted = NO;
    _browerBtn.enabled = NO;
    [_browerBtn.titleLabel setAlpha:0.4];

	[_browerBtn setBackgroundImage:[[UIImage imageNamed:@"message_btn_line_normal"] stretchableImageWithLeftCapWidth:6 topCapHeight:6] forState:UIControlStateNormal];
	[_browerBtn setBackgroundImage:[[UIImage imageNamed:@"message_btn_line_pressed"] stretchableImageWithLeftCapWidth:6 topCapHeight:6] forState:UIControlStateHighlighted];
    [_browerBtn setTitle:@"预览" forState:UIControlStateNormal];
    [_browerBtn setTitleColor:[UIColor rcsColorWithHexString:@"0fc381"] forState:UIControlStateNormal];
    [_browerBtn.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
    [_browerBtn addTarget:self action:@selector(browserBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:_browerBtn];

    NSString *selectCountTitle = [NSString stringWithFormat:@"发送"];
    
    _sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _sendBtn.frame = CGRectMake(rect.size.width - kBtnPaddingLeft - kBtnWidth, kBtnPaddingTop, kBtnWidth, kBtnHeight);
    _sendBtn.showsTouchWhenHighlighted = NO;
    _sendBtn.enabled = NO;
    [_sendBtn setBackgroundImage:[[UIImage imageNamed:@"message_btn_green_normal"] stretchableImageWithLeftCapWidth:6 topCapHeight:6] forState:UIControlStateNormal];
    [_sendBtn setBackgroundImage:[[UIImage imageNamed:@"message_btn_green_pressed"] stretchableImageWithLeftCapWidth:6 topCapHeight:6] forState:UIControlStateHighlighted];
    [_sendBtn setTitleColor:textcolor forState:UIControlStateNormal];
    [_sendBtn.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
    [_sendBtn setTitle:selectCountTitle forState:UIControlStateNormal];
    [_sendBtn addTarget:self action:@selector(sendPhotosBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:_sendBtn];
}


/**
 *  刷新UITableView
 */
- (void)reloadTableView
{
    [self initIndex];
    [_photosTableView reloadData];
    
}

#pragma mark - UITableViewDataSource

- (void)scrollToBottom:(BOOL)animation
{
    float groupCount = [self.photosArray count];
    NSInteger rows = ceil(groupCount/4);
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:rows - 1 inSection:0];
    
    if (indexPath.row >= 0)
    {
        
        
        [_photosTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows-1 inSection:0]
                             atScrollPosition:UITableViewScrollPositionBottom
                                     animated:animation];
        
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
    
    }
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    float groupCount = [self.photosArray count];
    return ceil(groupCount/4);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 5)];
    footView.backgroundColor = [UIColor clearColor];
    return footView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5.f;
}

-(UIView *)getCellMaskLayer:(UIButton *)cellButton
{
    for (id object in cellButton.subviews)
    {
        if ([object isKindOfClass:[UIView class]] && ((UIView *)object).tag == 5555)
        {
            UIView *view = (UIView *)object;
            return view;
        }
    }
    return nil;
}

-(RCSAlubmButton*)getCellButton:(FTAlbumPhotosCell*)cell Index:(NSInteger)index
{
    RCSAlubmButton* button = nil;
    if (index == 0)
    {
        button = cell.firstPhotoBtn;
    }
    else if (index == 1)
    {
        button = cell.secondPhotoBtn;
    }
    else if (index == 2)
    {
        button = cell.thirdPhotoBtn;
    }
    else
    {
        button = cell.fourPhotoBtn;
    }
    
    return button;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *photosIdentifier = @"PhotosIdentifier";
    FTAlbumPhotosCell *cell = [tableView dequeueReusableCellWithIdentifier:photosIdentifier];
    
    if (cell == nil)
    {
        cell = [[FTAlbumPhotosCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:photosIdentifier];
        cell.delegate = self;
    }

    NSInteger photosArrCount = [self.photosArray count];
    
    NSUInteger firstItem = indexPath.row * 4;
    NSUInteger lastItem  = firstItem + 4;
    
    for (int i = firstItem; i < lastItem; i++)
    {
        RCSAlubmButton *button = [self getCellButton:cell Index:(i-firstItem )];
        UIButton* selectBtn = (UIButton*)[button viewWithTag:kTag];

        if (self.albumType == AlbumType_MutiForSending)
        {
            if ([self isImageSelectIndex:i])
            {
                [selectBtn setImage:[UIImage imageNamed:@"message_album_select"] forState:UIControlStateNormal];
                [button setShowMaskLayer:YES];
            }
            else
            {
                [selectBtn setImage:[UIImage imageNamed:@"message_album_unselect"] forState:UIControlStateNormal];
                [button setShowMaskLayer:NO];
            }
        }
        else
        {
            selectBtn.enabled = NO;
            selectBtn.hidden = YES;
        }
        
        if (i >= photosArrCount)
        {
            button.hidden = YES;
            continue;
        }
        else
        {
            button.hidden = NO;
        }
        
        ALAsset *aset = [self.photosArray objectAtIndex:i];
        
        //筛选视频
        NSString *assetType = [aset valueForProperty:ALAssetPropertyType];
        if ([assetType isEqual:ALAssetTypeVideo])
        {
            //视频时长
            AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:aset.defaultRepresentation.url options:nil];
            
            NSInteger ceilTime = (double)avAsset.duration.value/avAsset.duration.timescale;
            
            [button setVideoIcon:[UIImage imageNamed:@"message_video_ablum_tag"] videoTime:[self calculateTime:ceilTime]];
            button.isPhotoType = NO;
            selectBtn.hidden = YES;
        }
        else
        {
            [button hideVideoView];
            button.isPhotoType = YES;
            if(self.albumType == AlbumType_SingleForPhoto || AlbumType_SingleForSendingForFile == self.albumType)
            {
                selectBtn.hidden = YES;
            }
            else
            {
                selectBtn.hidden = NO;
            }
        }
        
        UIImage *photo = [UIImage imageWithCGImage:aset.thumbnail];
        button.tag = i;
        [button setBackgroundImage:photo forState:UIControlStateNormal];
    }
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kPhotoViewHeight;
}

#pragma mark FTAlbumPhotosCellDelegate

/**
 *  点击照片预览
 *
 *  @param photoBtn 点中的button
 */
- (void)photoBtnPressed:(RCSAlubmButton *)photoBtn
{
    NSInteger btnTag = photoBtn.tag;
    
    if (!photoBtn.isPhotoType)
    {
        if (self.selectPhotosDict.count > 0)
        {
            //提示用户选择图片时不能选择视频
            [self showTipSelectView];
            return;
        }
        
        //跳转到视频预览界面
        ALAsset *asset = [self.photosArray objectAtIndex:btnTag];
        
        RCSBrowserVideoViewController *browserVideoVC = [[RCSBrowserVideoViewController alloc] initWithALAsset:asset];
        browserVideoVC.delegate = self.videoDelegate;
        browserVideoVC.isComeFromWiFi = self.isComeFromWiFi;
        
        if (AlbumType_SingleForSendingForFile == self.albumType)
        {
            browserVideoVC.selectSendType = SV_VideoFileTypeSend;
        }
        else
        {
            browserVideoVC.selectSendType = SV_VideoTypeSend;
        }
        
        browserVideoVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:browserVideoVC animated:YES];
        
    }
    else
    {
        if (self.albumType == AlbumType_MutiForSending)
        {
            //多图发送
            NSMutableArray *picArray = [[NSMutableArray alloc] initWithCapacity:1];
            
            NSInteger tmpTag = 0;
            
            //筛选相册里面的图片  过滤掉视频
            NSInteger count  = 0;
            
            for (int i = 0; i < self.photosArray.count; i++)
            {
                ALAsset *asset = [self.photosArray objectAtIndex:i];
                
                if ([[asset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
                {
                    [picArray addObject:asset];
                    
                    if (i == btnTag)
                    {
                        tmpTag = count;
                    }
                    count++;
                }
            }
            
             [self setChangeKey:_selBrowserAlbumPhotoKeyDict];
            FTBrowserAlbumController *browserView = [[FTBrowserAlbumController alloc] initWithSelectIndex:tmpTag
                                                                                            andAssetsDict:self.selectPhotosDict
                                                                                            andSelectKeys:self.selectPhotoKeys
                                                                                             andAllAssets:picArray isPartBrower:NO
                                                                                            andSendOrigin:_originBtn.selected];
            browserView.albumDelegate = self.albumDelegate;
            browserView.delegate = self;
            browserView.albumType = self.albumType;
            [self.navigationController pushViewController:browserView animated:YES];
        }
        else
        {
            //阅后即焚、修改头像、二维码
            [self.selectPhotosDict removeAllObjects];
            [self.selectPhotoKeys removeAllObjects];
            
            ALAsset *asset = [self.photosArray objectAtIndex:btnTag];
            NSString *photoKey = [NSString stringWithFormat:@"%ld",(long)btnTag];
            [self.selectPhotosDict setObject:asset forKey:photoKey];
            [self.selectPhotoKeys addObject:photoKey];
            
            NSMutableArray *tempArr = [[NSMutableArray alloc] initWithArray:[self.selectPhotosDict allValues]];
            
            if (self.photoCanEdit == YES)
            {
                //个人头像编辑
                ALAsset *asset = [self.photosArray objectAtIndex:btnTag];
                FTPhotoCropViewController *cropViewC = [[FTPhotoCropViewController alloc]init];
                
                if (self.albumType == AlbumType_SingleForPhoto && [asset.defaultRepresentation.UTI rangeOfString:@".gif"].location != NSNotFound)
                {
                    cropViewC.baseImage = [UIImage imageWithCGImage:asset.thumbnail];
                }
                else
                {
                    cropViewC.baseImage = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
                }
                
                cropViewC.imageDelegate = self;
                [self.navigationController pushViewController:cropViewC animated:YES];
            }
            else
            {
                FTBrowserAlbumController *browserView = [[FTBrowserAlbumController alloc] initWithSelectIndex:0
                                                                                                andAssetsDict:self.selectPhotosDict
                                                                                                andSelectKeys:self.selectPhotoKeys
                                                                                                 andAllAssets:tempArr
                                                                                                 isPartBrower:YES
                                                                                                andSendOrigin:_originBtn.selected];
                browserView.isComeFromWiFi = self.isComeFromWiFi;
                browserView.albumDelegate = self.albumDelegate;
                browserView.albumType = self.albumType;
                if (AlbumType_SingleForSendingForFile == self.albumType)
                {
                    browserView.isSendOrigin = YES;
                }
                [self.navigationController pushViewController:browserView animated:YES];
                [self.selectPhotoKeys removeAllObjects];
                [self.selectPhotosDict removeAllObjects];
            }
        }
    }
    
    
}


/**
 *	@brief	提示用户选择照片时不能选择视频
 *
 *	@return	N/A
 */
-(void)showTipSelectView
{
    
//    RCSBaseAlertView *alertView = [[RCSBaseAlertView alloc]initWithTitle:nil contentText:@"选择照片时不能选择视频"];
//    alertView.backgroundColor = [UIColor whiteColor];
//    [alertView show];
//
//    [alertView setCancelButtonTitle:@"确定" block:^{
//    }];
}

/**
 *  点击照片上选择按钮
 *
 *  @param button 点中的button
 */
-(void)selectPhotoBtnPressed:(UIButton *)button
{
    NSInteger btnTag = button.superview.tag;
    
    if ([self isImageSelectIndex:btnTag] == NO)
    {
        NSInteger selectCount = [self.selectPhotosDict allKeys].count;
        //选择
        if (self.albumType == AlbumType_MutiForSending && selectCount >= _intMaxAllowedPhotoCount)
        {
            //此处弹出最多只可发送9张的提示语
            //[self.view rcsmakeToast:@"最多只可发送9张"];
            return;
        }
        
        ALAsset *asset = [self.photosArray objectAtIndex:btnTag];
        NSString *photoKey = [NSString stringWithFormat:@"%ld",(long)btnTag];
        [self.selectPhotosDict setObject:asset forKey:photoKey];
        [self.selectPhotoKeys addObject:photoKey];
    }
    else
    {
        NSString *photoKey = [NSString stringWithFormat:@"%ld",(long)btnTag];
        [self.selectPhotosDict removeObjectForKey:photoKey];
        [self.selectPhotoKeys removeObject:photoKey];
    }
    
    NSString *selectCountTitle = nil;
    CGRect frame = _sendBtn.frame;
    
    if (self.selectPhotosDict.count > 0)
    {
        selectCountTitle = [NSString stringWithFormat:@"发送(%lu/%ld)",(unsigned long)[self.selectPhotosDict allKeys].count,(long)_intMaxAllowedPhotoCount];
        _sendBtn.enabled = YES;
        frame.size.width = KBtnSelWidth;
        _browerBtn.enabled = YES;
        [_browerBtn.titleLabel setAlpha:1];
        
    }
    else
    {
        frame.size.width = kBtnWidth;
        selectCountTitle = @"发送";
	    [self.sendBtn setTitle:selectCountTitle forState:UIControlStateNormal];
        _sendBtn.enabled = NO;
        _browerBtn.enabled = NO;
        [_browerBtn.titleLabel setAlpha:0.4];
    }
    
    frame.origin.x = self.view.frame.size.width - kBtnPaddingLeft - frame.size.width;
    _sendBtn.frame = frame;

    [self.sendBtn setTitle:selectCountTitle forState:UIControlStateNormal];

    [self.photosTableView reloadData];
}


/**
 *  原图勾选
 *
 */
- (void)selectOriginalPic:(id)sender
{
    UIButton *selectButton  = (UIButton *)[self.view viewWithTag:OriginBtnTag];
    if (selectButton.selected)
    {
        //取消
        [self.originBtn setBackgroundImage:[UIImage imageNamed:@"friend_content_photo_Artwork_Unselected"] forState:UIControlStateNormal];
    }
    else
    {
        //选择
        [self.originBtn setBackgroundImage:[UIImage imageNamed:@"friend_content_photo_Artwork"] forState:UIControlStateNormal];
    }
    selectButton.selected = !selectButton.selected;
}


/**
 *  判断该图片是否已经选择
 *
 *  @param index 当前索引
 *
 *  @return YES 已选择  ,NO 未选择
 */
-(BOOL)isImageSelectIndex:(NSInteger)index
{
    for (NSString* key in self.selectPhotoKeys)
    {
        if (key.intValue == index)
        {
            return YES;
        }
    }
    return NO;
}


/**
 *  点击预览按钮
 *
 *  @param sender 预览按钮，只预览选择的图片
 */
- (void)browserBtnPressed:(id)sender
{
    _bPreview = YES;
    NSMutableArray *assetsArr = [NSMutableArray arrayWithArray:[self.selectPhotosDict allValues]];
    FTBrowserAlbumController *browserView = [[FTBrowserAlbumController alloc] initWithSelectIndex:0
                                                                                    andAssetsDict:self.selectPhotosDict
                                                                                    andSelectKeys:self.selectPhotoKeys
                                                                                     andAllAssets:assetsArr
                                                                                     isPartBrower:YES
                                                                                    andSendOrigin:_originBtn.selected];
    browserView.albumDelegate = self.albumDelegate;
    browserView.delegate = self;
    browserView.albumType = self.albumType;
    [self.navigationController pushViewController:browserView animated:YES];
}


/**
 *  与预览图片界面照片选择数据一致
 *
 *  @param dict 预览界面字典
 */
-(void)foundTheALAsetAndRemoveWith:(NSMutableDictionary *)dict
{
    //预览界面返回相册界面
    if (_bPreview)
    {
        NSArray *tempValues = [dict allValues];
        NSUInteger count = self.selectPhotosDict.count;
        NSUInteger tempCount = dict.count;
        
        if (count > 0 && count >= tempCount)
        {
            NSArray *allKeys = [self.selectPhotosDict allKeys];
            NSArray *allValues = [self.selectPhotosDict allValues];
            
            for (int i = 0; i < count; i ++)
            {
                ALAsset *asset = (ALAsset *)[allValues objectAtIndex:i];
                
                if (![tempValues containsObject:asset])
                {
                    NSString *key = [allKeys objectAtIndex:i];
                    [self.selectPhotosDict removeObjectForKey:key];
                    [self.selectPhotoKeys removeObject:key];
                }
            }
        }
        _bPreview = NO;
        return;
    }
    _bPreview = NO;
    [self.selectPhotosDict removeAllObjects];
    [self.selectPhotoKeys removeAllObjects];
    
    [self.selectPhotosDict setValuesForKeysWithDictionary:dict];
    //[self.selectPhotoKeys addObjectsFromArray:[dict allKeys]];
    
    [self setChangeKey:_selAlbumPhotoKeyDict];
}

#pragma mark FTBrowserAlbumControllerDelegate

-(void)compareWithDict:(NSMutableDictionary *)tempDict
{
    if (tempDict.count == 0)
    {
        [self.selectPhotosDict removeAllObjects];
        [self.selectPhotoKeys removeAllObjects];
    }
    else
    {
        [self foundTheALAsetAndRemoveWith:tempDict];
    }
    
    NSString *selectCountTitle = nil;
    CGRect frame = _sendBtn.frame;
    
    if (self.selectPhotosDict.count > 0)
    {
        selectCountTitle = [NSString stringWithFormat:@"发送(%lu/%ld)",(unsigned long)[self.selectPhotosDict allKeys].count,(long)_intMaxAllowedPhotoCount];
        
        frame.size.width = KBtnSelWidth;
        _sendBtn.enabled = YES;
        _browerBtn.enabled = YES;
        [_browerBtn.titleLabel setAlpha:1];
    }
    else
    {
        frame.size.width = kBtnWidth;
        selectCountTitle = @"发送";
        _sendBtn.enabled = NO;
        _browerBtn.enabled = NO;
        [_browerBtn.titleLabel setAlpha:0.4];
    }
    
    frame.origin.x = self.view.frame.size.width - kBtnPaddingLeft - frame.size.width;
    _sendBtn.frame = frame;
    [self.sendBtn setTitle:selectCountTitle forState:UIControlStateNormal];
    [self.photosTableView reloadData];
}

/**
 *  发送按钮点击
 *
 *  @param sender 发送按钮
 */
- (void)sendPhotosBtnPressed:(id)sender
{
    __weak typeof(self) weakSelf = self;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if(weakSelf.albumDelegate && [weakSelf.albumDelegate respondsToSelector:@selector(albumDidFinishPickingWithInfo:IsOriginImg: withAlbumType:)])
        {
            NSMutableArray *selectPhotosArr = [[NSMutableArray alloc] init];
            
            for (int i = 0; i < weakSelf.selectPhotoKeys.count; i++)
            {
                NSString *key = [weakSelf.selectPhotoKeys objectAtIndex:i];
                ALAsset *tempALAset = (ALAsset *)[weakSelf.selectPhotosDict objectForKey:key];
                //MSG_LOG(@"%@",tempALAset.defaultRepresentation.url);

                if (_originBtn.selected)
                {
                    @autoreleasepool
                    {
                        NSUInteger size = (NSUInteger)[tempALAset.defaultRepresentation size];
                        uint8_t *buff = (uint8_t*)malloc(size);
                        NSError *err = nil;
                        [tempALAset.defaultRepresentation getBytes:buff fromOffset:0 length:size error:&err];
                        if (err)
                        {
                            //ErrorLog("发送原图：%s",err.localizedFailureReason.UTF8String);
                        }
                        
                        //不需要再调用free()
                        NSData *originScreenImgData = [NSData dataWithBytesNoCopy:buff length:size freeWhenDone:YES];
                        
                        if (originScreenImgData)
                        {
                            [selectPhotosArr addObject:originScreenImgData];
                        }
                    }
                }
                else
                {
                    NSData *fullScreenImgData = UIImageJPEGRepresentation([UIImage imageWithCGImage:tempALAset.defaultRepresentation.fullScreenImage], 1);
                    if (fullScreenImgData)
                    {
                        [selectPhotosArr addObject:fullScreenImgData];
                    }
                }
            }
            if (_originBtn.selected)
            {
                [weakSelf.albumDelegate albumDidFinishPickingWithInfo:selectPhotosArr IsOriginImg:YES withAlbumType:self.albumType];
            }
            else
            {
                [weakSelf.albumDelegate albumDidFinishPickingWithInfo:selectPhotosArr IsOriginImg:NO withAlbumType:self.albumType];
            }
        }
        
        [weakSelf dismissViewControllerAnimated:NO completion:nil];
    });
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark FTPhotoCropViewControllerDelegate
- (void)cropImageFinish:(UIImage*)image
{
    if(self.albumDelegate && [self.albumDelegate respondsToSelector:@selector(albumDidFinishPickingWithInfo:IsOriginImg: withAlbumType:)])
    {
        NSMutableArray* selectPhotosArr = [[NSMutableArray alloc]init];
        [selectPhotosArr addObject:image];
        [self.albumDelegate albumDidFinishPickingWithInfo:selectPhotosArr IsOriginImg:NO withAlbumType:self.albumType];
        [self dismissViewControllerAnimated:YES completion:nil];
    }

}

//设置相册界面Index字典 //add by lhb
-(void)initIndex
{
    NSInteger count = 0;
    for (int i = 0; i < self.photosArray.count; i++)
    {
        ALAsset *asset = [self.photosArray objectAtIndex:i];
        if ([[asset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
        {
            [self.selAlbumPhotoKeyDict setObject:[NSString stringWithFormat:@"%d",i] forKey:[NSString stringWithFormat:@"%ld",(long)count]];
            [self.selBrowserAlbumPhotoKeyDict setObject:[NSString stringWithFormat:@"%ld",(long)count] forKey:[NSString stringWithFormat:@"%d",i]];
            count++;
        }
    }
}

//转换相册图片Index //add by lhb
-(void)setChangeKey:(NSMutableDictionary*)changeDic
{
    NSMutableDictionary* dict = [self.selectPhotosDict mutableCopy];
    [self.selectPhotosDict removeAllObjects];
    [self.selectPhotoKeys removeAllObjects];
    
    if (dict && (0 < dict.count))
    {
        NSArray *allKeysArr = [dict allKeys];
        NSArray *allValuesArr = [dict allValues];
        
        NSInteger iCount = dict.count;
        for (int i = 0; i < iCount; i++)
        {
            ALAsset *asset = (ALAsset *)[allValuesArr objectAtIndex:i];
            if ([self.photosArray containsObject:asset])
            {
                NSString *key = [allKeysArr objectAtIndex:i];
                NSString *aKey = [changeDic objectForKey:key];
                if (aKey && (0 < aKey.length))
                {
                    if (![key isEqualToString:aKey])
                    {
                        key = aKey;
                    }
                }
                [self.selectPhotosDict setObject:asset forKey:key];
            }
        }
        [self.selectPhotoKeys addObjectsFromArray:[self.selectPhotosDict allKeys]];
    }
}

/* 计算显示的时间
 * @interval：传入的秒数
 * return：时间格式为mm:ss
 */
- (NSString*)calculateTime:(NSInteger)interval
{
    interval = interval % 3600;
    NSInteger minutes = interval / 60;
    interval = (interval % 60) < 1?0:(interval % 60);
    NSString* result = [NSString stringWithFormat:@"%02ld:%02ld", (long)minutes, (long)interval];
    
    return result;
}


@end



